package cz.zcu.fav.rat.qrcode;

import java.io.OutputStream;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BarcodeQRCode;
import com.itextpdf.text.pdf.PdfWriter;

import cz.zcu.fav.rat.beans.Object;
import cz.zcu.fav.rat.dataaccess.service.ObjectService;

@Component
public class ObjectQRCodeGenerator
{
	@Autowired
	ObjectService objectService;

	private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
			Font.BOLD);
	private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,
			Font.BOLD);

	private Logger logger = Logger.getLogger(ObjectQRCodeGenerator.class);

	public void createPDF(OutputStream output, Integer objectId)
	{
		Object obj = objectService.get(objectId);
		if (obj == null)
		{
			return;
		}
		Document doc = new Document();
		PdfWriter docWriter = null;

		try
		{
			docWriter = PdfWriter.getInstance(doc, output);
			doc.addAuthor("RAT - Reserve A Thing!");
			doc.addCreationDate();
			doc.addProducer();
			doc.addCreator("RAT automatic QR Code generator");
			doc.addTitle(obj.getName() + " QR print");
			doc.setPageSize(PageSize.LETTER);

			doc.open();

			Paragraph preface = new Paragraph();
			addEmptyLine(preface, 1);
			preface.add(new Paragraph(obj.getName(), catFont));

			addEmptyLine(preface, 1);
			preface.add(new Paragraph(
					"Identifier: " + obj.getIdentifier() ,smallBold));
			addEmptyLine(preface, 3);
		    doc.add(preface);
		    
		    
			BarcodeQRCode qrcode = new BarcodeQRCode(obj.getIdentifier(), 100,
					100, null);
			Image qrcodeImage = qrcode.getImage();
			qrcodeImage.setAbsolutePosition(0, 550);
			doc.add(qrcodeImage);
			

			qrcode = new BarcodeQRCode(obj.getIdentifier(), 200,
					200, null);
			qrcodeImage = qrcode.getImage();
			qrcodeImage.setAbsolutePosition(0, 350);
			doc.add(qrcodeImage);
			
			qrcode = new BarcodeQRCode(obj.getIdentifier(), 350,
					350, null);
			qrcodeImage = qrcode.getImage();
			qrcodeImage.setAbsolutePosition(0, 0);

			doc.add(qrcodeImage);

		} catch (DocumentException ex)
		{
			logger.error("error during PDF print", ex);
		} finally
		{
			if (doc != null)
			{
				doc.close();
			}
			if (docWriter != null)
			{
				docWriter.close();
			}
		}
	}

	private static void addEmptyLine(Paragraph paragraph, int number)
	{
		for (int i = 0; i < number; i++)
		{
			paragraph.add(new Paragraph(" "));
		}
	}

}
